<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      label-position="top"
    >
      <el-tabs v-model="activeTab" class="tenant-form-tabs">
        <!-- 基本信息 -->
        <el-tab-pane :label="$t('TenantManagement.BasicInfo')" name="basic">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="$t('TenantManagement.TenantName')" prop="name">
                <el-input
                  v-model="formData.name"
                  :placeholder="$t('TenantManagement.TenantNamePlaceholder')"
                  :maxlength="50"
                  show-word-limit
                  @blur="checkNameAvailability"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('TenantManagement.TenantCode')" prop="code">
                <el-input
                  v-model="formData.code"
                  :placeholder="$t('TenantManagement.TenantCodePlaceholder')"
                  :maxlength="20"
                  show-word-limit
                  style="text-transform: uppercase"
                  @blur="checkCodeAvailability"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item :label="$t('TenantManagement.Description')" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              :placeholder="$t('TenantManagement.DescriptionPlaceholder')"
              :maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="$t('TenantManagement.AdminEmail')" prop="adminEmail">
                <el-input
                  v-model="formData.adminEmail"
                  :placeholder="$t('TenantManagement.AdminEmailPlaceholder')"
                  type="email"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('TenantManagement.AdminPassword')" prop="adminPassword">
                <el-input
                  v-model="formData.adminPassword"
                  :placeholder="$t('TenantManagement.AdminPasswordPlaceholder')"
                  type="password"
                  show-password
                  :readonly="isEdit"
                />
                <div v-if="!isEdit" class="form-help">
                  <el-alert
                    :title="$t('TenantManagement.AdminPasswordHelp')"
                    type="info"
                    :closable="false"
                    show-icon
                  />
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="$t('TenantManagement.DatabaseType')" prop="databaseType">
                <el-select
                  v-model="formData.databaseType"
                  :placeholder="$t('TenantManagement.SelectDatabaseType')"
                  :disabled="isEdit"
                >
                  <el-option label="PostgreSQL" value="PostgreSQL" />
                  <el-option label="MySQL" value="MySQL" />
                  <el-option label="SQL Server" value="SqlServer" />
                  <el-option label="SQLite" value="SQLite" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('TenantManagement.ConnectionString')" prop="connectionString">
                <el-input
                  v-model="formData.connectionString"
                  :placeholder="$t('TenantManagement.ConnectionStringPlaceholder')"
                  type="password"
                  show-password
                  :readonly="isEdit"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>

        <!-- 功能设置 -->
        <el-tab-pane :label="$t('TenantManagement.Features')" name="features">
          <el-form-item :label="$t('TenantManagement.EnableFeatures')">
            <el-checkbox-group v-model="formData.enabledFeatures">
              <el-checkbox value="keycloakIntegration">
                {{ $t('TenantManagement.KeycloakIntegration') }}
              </el-checkbox>
              <el-checkbox value="fileStorage">
                {{ $t('TenantManagement.FileStorage') }}
              </el-checkbox>
              <el-checkbox value="aiAnalysis">
                {{ $t('TenantManagement.AIAnalysis') }}
              </el-checkbox>
              <el-checkbox value="advancedReporting">
                {{ $t('TenantManagement.AdvancedReporting') }}
              </el-checkbox>
              <el-checkbox value="apiAccess">
                {{ $t('TenantManagement.APIAccess') }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item :label="$t('TenantManagement.LimitSettings')">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item :label="$t('TenantManagement.MaxUsers')">
                  <el-input-number
                    v-model="formData.maxUsers"
                    :min="1"
                    :max="10000"
                    :step="1"
                    controls-position="right"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="$t('TenantManagement.MaxStorageGB')">
                  <el-input-number
                    v-model="formData.maxStorageGB"
                    :min="1"
                    :max="1000"
                    :step="1"
                    controls-position="right"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="$t('TenantManagement.MaxApiCallsPerDay')">
                  <el-input-number
                    v-model="formData.maxApiCallsPerDay"
                    :min="100"
                    :max="1000000"
                    :step="100"
                    controls-position="right"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
        </el-tab-pane>

        <!-- Keycloak配置 -->
        <el-tab-pane
          v-if="formData.enabledFeatures.includes('keycloakIntegration')"
          :label="$t('TenantManagement.KeycloakConfig')"
          name="keycloak"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="$t('TenantManagement.RealmName')" prop="keycloakRealm">
                <el-input
                  v-model="formData.keycloakRealm"
                  :placeholder="$t('TenantManagement.RealmNamePlaceholder')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('TenantManagement.RealmDisplayName')" prop="keycloakRealmDisplayName">
                <el-input
                  v-model="formData.keycloakRealmDisplayName"
                  :placeholder="$t('TenantManagement.RealmDisplayNamePlaceholder')"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item :label="$t('TenantManagement.CustomTheme')">
            <el-radio-group v-model="formData.keycloakTheme">
              <el-radio value="matrix">{{ $t('TenantManagement.MatrixTheme') }}</el-radio>
              <el-radio value="custom">{{ $t('TenantManagement.CustomTheme') }}</el-radio>
              <el-radio value="default">{{ $t('TenantManagement.DefaultTheme') }}</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item :label="$t('TenantManagement.SSOSettings')">
            <el-checkbox-group v-model="formData.keycloakSettings">
              <el-checkbox value="socialLogin">
                {{ $t('TenantManagement.EnableSocialLogin') }}
              </el-checkbox>
              <el-checkbox value="mfa">
                {{ $t('TenantManagement.EnableMFA') }}
              </el-checkbox>
              <el-checkbox value="rememberMe">
                {{ $t('TenantManagement.EnableRememberMe') }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>

        <!-- 高级设置 -->
        <el-tab-pane :label="$t('TenantManagement.Advanced')" name="advanced">
          <el-form-item :label="$t('TenantManagement.Timezone')" prop="timezone">
            <el-select
              v-model="formData.timezone"
              :placeholder="$t('TenantManagement.SelectTimezone')"
              filterable
            >
              <el-option
                v-for="tz in timezones"
                :key="tz.value"
                :label="tz.label"
                :value="tz.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item :label="$t('TenantManagement.CustomSettings')">
            <el-button type="primary" plain @click="addCustomSetting">
              <el-icon><Plus /></el-icon>
              {{ $t('TenantManagement.AddCustomSetting') }}
            </el-button>

            <div v-if="formData.customSettings && formData.customSettings.length > 0" class="custom-settings">
              <el-row
                v-for="(setting, index) in formData.customSettings"
                :key="index"
                :gutter="10"
                class="setting-item"
              >
                <el-col :span="8">
                  <el-input
                    v-model="setting.key"
                    :placeholder="$t('TenantManagement.SettingKey')"
                  />
                </el-col>
                <el-col :span="12">
                  <el-input
                    v-model="setting.value"
                    :placeholder="$t('TenantManagement.SettingValue')"
                  />
                </el-col>
                <el-col :span="4">
                  <el-button type="danger" plain @click="removeCustomSetting(index)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </el-col>
              </el-row>
            </div>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">{{ $t('Common.Cancel') }}</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          {{ isEdit ? $t('Common.Update') : $t('Common.Create') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { tenantService } from '@/services/tenant.service'
import { abpService } from '@/services/abp.service'
import type { Tenant, CreateTenantRequest, UpdateTenantRequest } from '@/types/abp'

interface Props {
  modelValue: boolean
  tenant?: Tenant | null
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const loading = ref(false)
const activeTab = ref('basic')

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const isEdit = computed(() => !!props.tenant?.id)

const dialogTitle = computed(() =>
  isEdit.value ? $t('TenantManagement.EditTenant') : $t('TenantManagement.CreateTenant')
)

// 表单数据
const formData = reactive({
  name: '',
  code: '',
  description: '',
  adminEmail: '',
  adminPassword: '',
  databaseType: 'PostgreSQL',
  connectionString: '',
  enabledFeatures: [] as string[],
  maxUsers: 100,
  maxStorageGB: 10,
  maxApiCallsPerDay: 10000,
  keycloakRealm: '',
  keycloakRealmDisplayName: '',
  keycloakTheme: 'matrix',
  keycloakSettings: [] as string[],
  timezone: 'UTC',
  customSettings: [] as Array<{ key: string; value: string }>
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: $t('TenantManagement.TenantNameRequired'), trigger: 'blur' },
    { min: 2, max: 50, message: $t('TenantManagement.TenantNameLength'), trigger: 'blur' }
  ],
  code: [
    { required: true, message: $t('TenantManagement.TenantCodeRequired'), trigger: 'blur' },
    { pattern: /^[A-Z][A-Z0-9]*$/, message: $t('TenantManagement.TenantCodePattern'), trigger: 'blur' }
  ],
  adminEmail: [
    { required: true, message: $t('TenantManagement.AdminEmailRequired'), trigger: 'blur' },
    { type: 'email', message: $t('TenantManagement.AdminEmailFormat'), trigger: 'blur' }
  ],
  adminPassword: [
    { required: !isEdit.value, message: $t('TenantManagement.AdminPasswordRequired'), trigger: 'blur' },
    { min: 8, message: $t('TenantManagement.AdminPasswordLength'), trigger: 'blur' }
  ],
  databaseType: [
    { required: true, message: $t('TenantManagement.DatabaseTypeRequired'), trigger: 'change' }
  ],
  connectionString: [
    { required: !isEdit.value, message: $t('TenantManagement.ConnectionStringRequired'), trigger: 'blur' }
  ]
}

// 时区选项
const timezones = [
  { label: 'UTC (UTC+0)', value: 'UTC' },
  { label: '北京时间 (UTC+8)', value: 'Asia/Shanghai' },
  { label: '东京时间 (UTC+9)', value: 'Asia/Tokyo' },
  { label: '纽约时间 (UTC-5)', value: 'America/New_York' },
  { label: '伦敦时间 (UTC+0)', value: 'Europe/London' },
  { label: '巴黎时间 (UTC+1)', value: 'Europe/Paris' }
]

// 监听租户数据变化
watch(() => props.tenant, (newTenant) => {
  if (newTenant) {
    Object.assign(formData, {
      name: newTenant.name || '',
      code: newTenant.code || '',
      description: newTenant.description || '',
      adminEmail: newTenant.adminEmailAddress || '',
      databaseType: newTenant.databaseType || 'PostgreSQL',
      connectionString: newTenant.connectionString || '',
      enabledFeatures: newTenant.enabledFeatures || [],
      maxUsers: newTenant.maxUsers || 100,
      maxStorageGB: newTenant.maxStorageGB || 10,
      maxApiCallsPerDay: newTenant.maxApiCallsPerDay || 10000,
      keycloakRealm: newTenant.keycloakRealm || '',
      keycloakRealmDisplayName: newTenant.keycloakRealmDisplayName || '',
      keycloakTheme: newTenant.keycloakTheme || 'matrix',
      keycloakSettings: newTenant.keycloakSettings || [],
      timezone: newTenant.timezone || 'UTC',
      customSettings: newTenant.customSettings || []
    })
  } else {
    resetForm()
  }
}, { immediate: true })

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    code: '',
    description: '',
    adminEmail: '',
    adminPassword: '',
    databaseType: 'PostgreSQL',
    connectionString: '',
    enabledFeatures: [],
    maxUsers: 100,
    maxStorageGB: 10,
    maxApiCallsPerDay: 10000,
    keycloakRealm: '',
    keycloakRealmDisplayName: '',
    keycloakTheme: 'matrix',
    keycloakSettings: [],
    timezone: 'UTC',
    customSettings: []
  })
  activeTab.value = 'basic'
}

// 检查名称可用性
const checkNameAvailability = async () => {
  if (!formData.name || isEdit.value) return

  try {
    const tenants = await tenantService.getTenantList({ filter: formData.name })
    if (tenants.items.some(t => t.name.toLowerCase() === formData.name.toLowerCase())) {
      formRef.value?.validateField('name')
      ElMessage.warning($t('TenantManagement.TenantNameExists'))
    }
  } catch (error) {
    console.error('检查名称可用性失败:', error)
  }
}

// 检查代码可用性
const checkCodeAvailability = async () => {
  if (!formData.code || isEdit.value) return

  try {
    const tenants = await tenantService.getTenantList({ filter: formData.code })
    if (tenants.items.some(t => t.code.toLowerCase() === formData.code.toLowerCase())) {
      formRef.value?.validateField('code')
      ElMessage.warning($t('TenantManagement.TenantCodeExists'))
    }
  } catch (error) {
    console.error('检查代码可用性失败:', error)
  }
}

// 添加自定义设置
const addCustomSetting = () => {
  if (!formData.customSettings) {
    formData.customSettings = []
  }
  formData.customSettings.push({ key: '', value: '' })
}

// 删除自定义设置
const removeCustomSetting = (index: number) => {
  formData.customSettings.splice(index, 1)
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    loading.value = true

    if (isEdit.value) {
      const updateRequest: UpdateTenantRequest = {
        name: formData.name,
        code: formData.code,
        description: formData.description,
        adminEmailAddress: formData.adminEmail,
        enabledFeatures: formData.enabledFeatures,
        maxUsers: formData.maxUsers,
        maxStorageGB: formData.maxStorageGB,
        maxApiCallsPerDay: formData.maxApiCallsPerDay,
        keycloakRealm: formData.keycloakRealm,
        keycloakRealmDisplayName: formData.keycloakRealmDisplayName,
        keycloakTheme: formData.keycloakTheme,
        keycloakSettings: formData.keycloakSettings,
        timezone: formData.timezone,
        customSettings: formData.customSettings
      }

      await tenantService.updateTenant(props.tenant!.id, updateRequest)
      ElMessage.success($t('TenantManagement.UpdateTenantSuccess'))
    } else {
      const createRequest: CreateTenantRequest = {
        name: formData.name,
        code: formData.code,
        description: formData.description,
        adminEmailAddress: formData.adminEmail,
        adminPassword: formData.adminPassword,
        databaseType: formData.databaseType,
        connectionString: formData.connectionString,
        enabledFeatures: formData.enabledFeatures,
        maxUsers: formData.maxUsers,
        maxStorageGB: formData.maxStorageGB,
        maxApiCallsPerDay: formData.maxApiCallsPerDay,
        keycloakRealm: formData.keycloakRealm,
        keycloakRealmDisplayName: formData.keycloakRealmDisplayName,
        keycloakTheme: formData.keycloakTheme,
        keycloakSettings: formData.keycloakSettings,
        timezone: formData.timezone,
        customSettings: formData.customSettings
      }

      await tenantService.createTenant(createRequest)
      ElMessage.success($t('TenantManagement.CreateTenantSuccess'))
    }

    emit('success')
    handleClose()
  } catch (error: any) {
    console.error('保存租户失败:', error)

    if (error.response?.data?.error?.details) {
      ElMessage.error(error.response.data.error.details)
    } else if (error.response?.data?.error?.message) {
      ElMessage.error(error.response.data.error.message)
    } else {
      ElMessage.error($t('TenantManagement.SaveTenantFailed'))
    }
  } finally {
    loading.value = false
  }
}

// 处理关闭
const handleClose = () => {
  if (loading.value) return

  dialogVisible.value = false
  setTimeout(() => {
    formRef.value?.resetFields()
    resetForm()
  }, 300)
}
</script>

<style scoped>
.tenant-form-tabs {
  margin: -20px;
}

.form-help {
  margin-top: 5px;
  font-size: 12px;
}

.custom-settings {
  margin-top: 10px;
}

.setting-item {
  margin-bottom: 10px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-tabs__content) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
</style>